﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Diagnostics;

namespace MonolithHelper
{
   
        public class ProcessHelper
        {
            // The OpenProcessToken function opens the access token associated with a process.
            [DllImport("advapi32.dll", SetLastError = true)]
            private static extern bool OpenProcessToken(IntPtr ProcessHandle, UInt32 DesiredAccess, out IntPtr TokenHandle);

            // Closes an open object handle.
            [DllImport("kernel32.dll", SetLastError = true)]
            [return: MarshalAs(UnmanagedType.Bool)]
            private static extern bool CloseHandle(IntPtr hObject);

            // Required to query an access token.
            private static uint TOKEN_QUERY = 0x0008;

            /// <summary>
            /// Gets the process owner.
            /// </summary>
            /// <value>The process owner.</value>
            public static string CurrentProcessOwner
            {
                get
                {
                    return GetCurrentProcessOwner(Process.GetCurrentProcess().Handle);
                }
            }

            public static string GetCurrentProcessOwner(IntPtr processHandle)
            {
                IntPtr ptr = IntPtr.Zero;
                try
                {
                    OpenProcessToken(processHandle, TOKEN_QUERY, out ptr);
                    WindowsIdentity wi = new WindowsIdentity(ptr);
                    return wi.Name.Substring(wi.Name.IndexOf(@"\") + 1);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    if (ptr != IntPtr.Zero)
                    {
                        CloseHandle(ptr);
                    }
                }
            }
        }
 }

